package com.example.demo.程序员面试金典;

import com.example.demo.leetcode100题.ListNode;

/**
 * @author：zzc
 * @date: 2022/9/8
 */
public class 链表求和 {

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode(int x) { val = x; }
     * }
     */

    // todo
    //同时遍历两链表，求节点的和与进位。
    class Solution {

        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int carry = 0 ;
            ListNode dummy = new ListNode(-1);
            ListNode cur = dummy;
            while (l1 != null || l2 != null || carry != 0) {
                int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
                carry = s/10;
                cur.next = new ListNode(s % 10);
                cur = cur.next;
                l1 = l1 == null ? null : l1.next;
                l2 = l2 == null ? null : l2.next;
            }
            return dummy.next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        while (l1 != null || l2 != null || carry != 0) {
            int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
            carry = s / 10;
            cur.next = new ListNode(s % 10);
            cur = cur.next;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        return dummy.next;
    }


}
